package com.tianji.learning.mq;


import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


/**
 * 支付或报名成功后，接受MQ消息，添加课程到课程表
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService learningLessonService;

    /**
     * 下单后将课程信息保存到课程表中
     *
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.pay.insertLesson", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY))
    public void listenerLesson(OrderBasicDTO order) {
        // 参数校验
        if (ObjectUtil.hasEmpty(order, order.getUserId(), order.getCourseIds())) {
            log.error("处理用户下单后保存课程信息的MQ调用失败");
            return;
        }
        log.debug("监听到用户{}的订单{}，需要添加课程{}到课表中",order.getUserId(),order.getOrderId(),order.getCourseIds());
        learningLessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }


    /**
     * 用户退款后通过MQ异步删除课程信息
     *
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.refund.deleteLesson", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY))
    public void listenerDeleteLesson(OrderBasicDTO order) {
        // 参数校验
        if (ObjectUtil.hasEmpty(order, order.getUserId(), order.getCourseIds())) {
            log.error("处理用户退款后删除课程信息的MQ调用失败");
            return;
        }
        log.debug("监听到用户{}的订单{}要退款，需要删除课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        learningLessonService.deleteCourseFromLesson(order.getUserId(), order.getCourseIds().get(0));
    }

}
